package com.code2roc.jarmanage.job;

import com.code2roc.jarmanage.util.CMDUtil;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConfigUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import org.apache.commons.io.FileUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@DisallowConcurrentExecution
public class LogFileRollJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        boolean logFileRoll = ConvertUtil.convert2Boolean(ConfigUtil.getConfigValue("logFileRoll"));
        int logFileRollSize = ConvertUtil.convert2Int(ConfigUtil.getConfigValue("logFileRollSize"));
        if (logFileRoll) {
            List<File> depolyLogFileList = (List<File>) FileUtils.listFiles(new File("depoly"), new String[]{"out.log"}, true);
            for (int i = 0; i < depolyLogFileList.size(); i++) {
                File file = depolyLogFileList.get(i);
                if (file.length() > 1024 * 1024 * logFileRollSize) {
                    String oldFilePath = file.getAbsolutePath();
                    String newFilePath = file.getAbsolutePath() + CommonUtil.getDateTagToSecond();
                    String command = "cp " + oldFilePath + " " + newFilePath;
                    CMDUtil.executeLinuxCommand(command);
                    command = "cat /dev/null > " + oldFilePath + " ";
                    CMDUtil.executeLinuxCommand(command);
                }
            }

            depolyLogFileList = (List<File>) FileUtils.listFiles(new File("depoly-war"), new String[]{"out.log"}, true);
            for (int i = 0; i < depolyLogFileList.size(); i++) {
                File file = depolyLogFileList.get(i);
                if (file.length() > 1024 * 1024 * logFileRollSize) {
                    String oldFilePath = file.getAbsolutePath();
                    String newFilePath = file.getAbsolutePath() + CommonUtil.getDateTagToSecond();
                    String command = "cp " + oldFilePath + " " + newFilePath;
                    CMDUtil.executeLinuxCommand(command);
                    command = "cat /dev/null > " + oldFilePath + " ";
                    CMDUtil.executeLinuxCommand(command);
                }
            }
        }
    }
}
